package com.doyens.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doyens.common.R;
import com.doyens.entity.User;
import com.doyens.service.UserService;
import com.doyens.utils.SMSUtils;
import com.doyens.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取到手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            //生成随机的4位数验证码
           String code =  ValidateCodeUtils.generateValidateCode(4).toString();
           log.info("code={}",code);
            //调用阿里云的提供的短信验证码发送短信
           // SMSUtils.sendMessage("德源商城","SMS_206545650",phone,code);
            //把验证码保存到session中
          //  session.setAttribute(phone,code);
            //将生成的验证码放到redis, 设置有效期5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码发送成功..");
        }
        return R.error("短信发送失败..");
    }


    //登录功能
    @PostMapping("/login")
    public R<User>  login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //获取到手机号
        String phone = map.get("phone").toString();

        //获取前台输入的验证码
        String code = map.get("code").toString();

        //从session中取出验证码
       // String codeInSession = (String) session.getAttribute(phone);
        //从redis中获取验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        //进行验证码比对,
        if (codeInSession !=null && codeInSession.equals(code)){
            //如果比对成功, 登录成功.
            LambdaQueryWrapper<User>  lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(lambdaQueryWrapper);
            //判断, 当前这个手机号,是否在数据库中存在,如果不存
            if (user == null){
                // 做一个insert操作.
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            // 登录成功后,删除验证码
            redisTemplate.delete(phone);


            return R.success(user);
        }
        return R.error("登录失败..");
    }

}
